package listbyorder.access001_100.test33;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/18 10:05
 */
public class Solution3 {

    // 实现LogN级时间复杂度
    // 首先双指针找到数组中最小元素，从当前元素开始为start指针，当前位置加上len作为end指针，进行二分查找遍历
    public int search(int[] nums, int target) {
        if (nums.length == 0) return -1;
        // 二分找到数组中最小的元素
        int start = 0;
        int end = nums.length - 1;
        while (start < end) {
            int mid = (start + end) >>> 1;
            if (nums[mid] > nums[end]) {
                start = mid + 1;
            } else {
                end = mid;
            }
        }
        // 此处的start就是最小元素
        int len = nums.length;
        end = start + len - 1;
        while (start <= end) {
            int mid = (start + end) >>> 1;
            if (nums[mid % len] > target) {
                end = mid - 1;
            } else if (nums[mid % len] < target) {
                start = mid + 1;
            } else {
                return mid % len;
            }
        }
        return -1;
    }

}
